package com.example.whm.lib;



import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Semaphore;

import org.holoeverywhere.app.Application;
import org.holoeverywhere.preference.SharedPreferences;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import cn.db.Msg;

import com.alibaba.fastjson.JSONObject;
import com.example.whm.FlowList;
import com.example.whm.MainActivity;
import com.example.whm.Profile;
import com.example.whm.R;
import com.example.whm.model.User;
import com.koushikdutta.async.callback.CompletedCallback;
import com.koushikdutta.async.http.AsyncHttpClient;
import com.koushikdutta.async.http.AsyncHttpClient.WebSocketConnectCallback;
import com.koushikdutta.async.http.WebSocket;
import com.koushikdutta.async.http.WebSocket.StringCallback;

public class Service_ extends Service {

	
	 WebSocket w;
	 private NotificationManager mNM;
	 Map<String, Handler> hmap=new HashMap<String, Handler>();
	  SharedPreferences sp;
	 
	 
	 
	 public Map<String, Handler> getHmap() {
		return hmap;
	}

	public void setHmap(Map<String, Handler> hmap) {
		this.hmap = hmap;
	}

	public WebSocket getW() {
		return w;
	}

	public void setW(WebSocket w) {
		this.w = w;
	}


	public class MyBinder extends Binder{
	        
	        public Service_ getService(){
	            return Service_.this;
	        }
	    }
	    
	    private MyBinder myBinder = new MyBinder();
	
	
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return myBinder;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		sp=((Application)getApplication()).getSharedPreferences("whm",Context.MODE_PRIVATE);
		 mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		 System.out.println("################## onCreate");
		 init_websocket();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (w.isOpen()) {
			w.close();
		}
		System.out.println("onDestroy==============");
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
	}
	
	
	 private void showNotification(String t,String con,Intent i) {
	        // In this sample, we'll use the same text for the ticker and the expanded notification
	        CharSequence text = t;

	        // Set the icon, scrolling text and timestamp
	        Notification notification = new Notification(R.drawable.ic_launcher, t,
	                System.currentTimeMillis());

	        // The PendingIntent to launch our activity if the user selects this notification
	        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
	               i, 0);

	        // Set the info for the views that show in the notification panel.
	        notification.setLatestEventInfo(this, t,
	                       con, contentIntent);

	        // Send the notification.
	        mNM.notify(1, notification);
	    }
	 
	
	public void init_websocket(){
		  
		//System.out.println("s==============="+s);
		        final Semaphore semaphore = new Semaphore(0);
		        String sessionid;
		        if (sp.getString("sessionid", null)!=null) {
		        	System.out.println("sp.getString sessionid !=null  ---"+sp.getString("sessionid", null));
		        	sessionid=sp.getString("sessionid", null);
				}else{
				      sessionid=UUID.randomUUID().toString();
				      client.pre_cache_put(sp, "sessionid", sessionid); 
				}
		       
		        String url = "http://"+sp.getString("host", "")+":9000/api/chat/"+sessionid;
		        if (sp.getString("user", null)!=null) {
		        	User u=JSONObject.parseObject(sp.getString("user",null), User.class);
		        	
		        	 url = "http://"+sp.getString("host", "")+":9000/api/chat/"+sessionid+"?u="+u.getId();
				}
		        System.out.println("init_websocket################### url="+url); 
		        AsyncHttpClient.getDefaultInstance().websocket(url, null, new WebSocketConnectCallback() {
				    @Override
				    public void onCompleted(Exception ex, WebSocket webSocket) {
				       System.out.println("---------------complete");
				       if (webSocket!=null&&webSocket.isOpen()) {
				    	   System.out.println(" webSocket.isOpen()="+webSocket.isOpen());
				    	   w = webSocket;
					  
				      
				       
				     
				        webSocket.setStringCallback(new StringCallback() {
				            @Override
				            public void onStringAvailable(final String s) {
				                
				              System.out.println("StringCallback======"+s);
				              // showNotification(s);
				            	Msg m= JSONObject.parseObject(s, Msg.class);
				            	switch (m.getType()) {
								case 2:
									sendmsg(m);
									break;
	                            case 3:
	                            	Intent i=new Intent(Service_.this, Profile.class);
	                   			 if (i.getExtras()!=null) {
	                   				  i.getExtras().putString("id", m.getTo_u_id());
	                   			}else{
	                   				Bundle b=new Bundle();
	                   				b.putString("id",m.getTo_u_id());
	                   				i.putExtras(b);
	                   			}
	                            	
									showNotification("follow msg", m.getFrom()+" follow you", i);
	                            	
	                            	
									break;
								default:
									break;
								}
				            	
				                semaphore.release();
				            }
				        });
				        webSocket.setClosedCallback(new CompletedCallback() {
							
							@Override
							public void onCompleted(Exception arg0) {
								// TODO Auto-generated method stub
								System.out.println("========closed");
							}
						});
				        webSocket.setEndCallback(new CompletedCallback() {
							
							@Override
							public void onCompleted(Exception arg0) {
								// TODO Auto-generated method stub
								System.out.println("========end");
								
							}
						});
				        
				       }
				        
				        
				    }
				});
		        
		       // assertTrue(semaphore.tryAcquire(TIMEOUT, TimeUnit.MILLISECONDS));
		    
		
		    }
	public void sendmsg(Msg m){
		if (m!=null&&m.getType()==2) {
    		Message msg=Message.obtain();
    		msg.what=1;
    		msg.obj=m;
    		System.out.println("sendmsg,m="+m);
			hmap.get(FlowList.class.getSimpleName()).sendMessage(msg);
		}
	}
	

}
